#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2018/9/20 11:40
@desc
"""
# 导入Thrift模块
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

# 导入自己生成的hbase python模块
from hbasepython.hbase import THBaseService
from hbasepython.hbase.ttypes import *


class HbaseConnect:
    # 创建 Socket连接，到CSparkMaster:9090
    def __init__(self, netloc, port, table):
        self.tableName = table
        self.transport = TTransport.TBufferedTransport(
            TSocket.TSocket(netloc, port))
        self.protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
        self.client = THBaseService.Client(self.protocol)
        self.transport.open()

    # 析构函数，关闭连接
    def __del__(self):
        self.transport.close()

    def put(self, tablename, rowkey, family, qualifier, value):
        tColumnValue = TColumnValue(family=family, qualifier=qualifier, value=value)
        vals = [tColumnValue]
        # 指定行和列
        tput = TPut(rowkey, vals)
        # 调用put执行插入
        self.client.put(tablename, tput)

    def putByColumnValues(self, tablename, rowkey, columnValues):
        tput = TPut(rowkey, columnValues)
        self.client.put(tablename, tput)

    def putByTPut(self, tablename, tput):
        self.client.put(tablename, tput)

    def get(self, tablename, rowkey, family, qualifier):
        # 查询
        tcolumn = TColumn(family, qualifier)
        cols = [tcolumn]
        tget = TGet(rowkey, cols)
        return self.client.get(tablename, tget)

    def getByColumnValues(self, tablename, rowkey=None, columns=None, timestamp=None, timeRange=None, maxVersions=None,
                          filterString=None, attributes=None, authorizations=None, ):
        # 查询
        tget = TGet(rowkey, columns, timestamp, timeRange, maxVersions, filterString, attributes, authorizations)
        return self.client.get(tablename, tget)

    def getByTGet(self, tablename, tget):
        return self.client.get(tablename, tget)

    def scan(self, tablename, startrow, stoprow, cols, catch, maxversion, timerange, filterstr, batchsize, attributes,
             auth, reverse, numrows):
        # 扫描
        tscan = TScan(startRow=startrow, stopRow=stoprow, columns=cols, caching=catch, maxVersions=maxversion,
                      timeRange=timerange, filterString=filterstr, batchSize=batchsize, attributes=attributes,
                      authorizations=auth, reversed=reverse)
        return self.client.getScannerResults(table=tablename, tscan=tscan, numRows=numrows)

    def scanByTScan(self, tablename, tscan, numrows):
        return self.client.getScannerResults(table=tablename, tscan=tscan, numRows=numrows)
